package com.pdfbox.sample.md2pdf;

import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;

/**
 * AI 生成
 */
public class MarkdownToPdfWithChinese {

    public static void main(String[] args) throws Exception {
        String aiPdfPath = "E:/PdfBox_Examples/aiMd2Pdf.pdf";
        // 1. 包含中文的Markdown文本
        String markdown = "# 中文测试文档\n\n" +
                "## 目录\n" +
                "1. [简介](#简介)\n" +
                "2. [示例](#示例)\n\n" +
                "## 简介\n" +
                "这是一个测试**中文PDF生成**的文档。\n\n" +
                "## 示例\n" +
                "- 中文列表项1\n" +
                "- 中文列表项2\n\n" +
                "```java\nSystem.out.println(\"中文\");\n```";

        // 2. 将Markdown转为HTML
        String html = markdownToHtml(markdown);

        // 3. 包装为XHTML（添加中文字体支持）
        String xhtml = wrapAsXhtml(html);

        // 4. 生成PDF（需指定中文字体）
        htmlToPdf(xhtml, aiPdfPath);
    }

    private static String markdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    private static String wrapAsXhtml(String htmlBody) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                "<head>\n" +
                "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +
                "    <title>中文PDF</title>\n" +
                "    <style>\n" +
                "        body { font-family: SimSun; }\n" +  // 指定中文字体
                "        h1 { color: #2c3e50; }\n" +
                "        pre { background: #f8f8f8; padding: 10px; }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" + htmlBody + "\n</body>\n</html>";
    }

    private static void htmlToPdf(String xhtml, String outputPath) throws Exception {
        try (OutputStream os = new FileOutputStream(outputPath)) {
            ITextRenderer renderer = new ITextRenderer();

            // 关键：注册中文字体
            String fontPath = "C:/Windows/Fonts/simsun.ttc"; // Windows系统宋体路径
            renderer.getFontResolver().addFont(fontPath, "Identity-H", true);

            renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(os);
            System.out.println("中文PDF生成成功: " + outputPath);
        }
    }
}